package main

import (
    "net/http"
    "fmt"
    "github.com/unrolled/render"
    "strconv"
)

type vars struct {
    University string
    Age int
}

type userinfo struct {
    Username string
    Password string
}

func main() {
    r := render.New(render.Options{})
    mux := http.NewServeMux()

    /* 首页 */
    mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        if req.URL.Path == "/" {
            r.Text(w, http.StatusOK, "服务计算第7次作业")
        } else {
            r.Text(w, http.StatusNotFound, "404")
        }
    })

    /* 静态文件 */
    mux.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("./assets/"))))

    /* 简单API：返回实数的平方 */
    mux.HandleFunc("/api/square", func(w http.ResponseWriter, req *http.Request) {
        params := req.URL.Query()
        if val, ok := params["x"]; ok {
            if f, err := strconv.ParseFloat(val[0], 64); err == nil {
                r.JSON(w, http.StatusOK, struct{Y float64 `json:"y"`}{f * f})
                return
            }
        }
        r.JSON(w, http.StatusOK, struct{Err string `json:"err"`}{"wrong format"})
    })

    /* 测试文件，内含JS发请求，以及提交表单 */
    info := vars{"SYSU", 18}
    mux.HandleFunc("/test", func(w http.ResponseWriter, req *http.Request) {
        r.HTML(w, http.StatusOK, "test", info)
    })

    /* 提交表单后的页面 */
    mux.HandleFunc("/signin", func(w http.ResponseWriter, req *http.Request) {
        if req.Method != "POST" {
            return
        }
        req.ParseForm()
        user := userinfo{req.PostForm["username"][0], req.PostForm["password"][0]}
        r.HTML(w, http.StatusOK, "signin", user)
    })

    fmt.Println("start listening")
    http.ListenAndServe("127.0.0.1:8888", mux)
}
